package cn.tedu.boot32.controller;

import cn.tedu.boot32.entity.User;
import cn.tedu.boot32.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;


/**
 * @Classname: UserController
 * @Author: bromide
 * @CreateTime: 2022/5/12--16:23
 * @Version: V1.0
 * @Description:
 */
@RestController
public class UserController {
    @Autowired(required = false)
    UserMapper mapper;

    @RequestMapping("/reg")
    public int reg(@RequestBody User user) {
        if (mapper.selectByUsername(user.getUsername())==null){
            //如果是空,那么可以注册
            mapper.insert(user);
            return 1;
        }else {
            return 2;
        }
    }

    @RequestMapping("/login")
    public int login(@RequestBody User user){
        User user1 = mapper.selectByUsername(user.getUsername());
        if (user1==null){
            //如果是空,说明用户不存在
            return 3;
        }else {
            if (user1.getPassword().equals(user.getPassword())){
                return 1;
            }else {
                //密码错误
                return 2;
            }
        }
    }

    @RequestMapping("/select")
    public String select(){
        List<User> list=mapper.select();
        String html = "<table border=1>";
        html+="<caption>用户列表</caption>";
        html+="<tr><td>id</td><td>用户名</td><td>密码</td><td>昵称</td><td>操作1</td><td>操作2</td></tr>";
        for (User user : list){
            html+="<tr><td>"+user.getId()+"</td><td>"+user.getUsername()+"</td><td>"+user.getPassword()+
                    "</td><td>"+user.getNickname()+"</td><td><a href='/delete?username="+user.getUsername()+"'>删除</a>" +
                    "</td><td><a href='/update.html'>修改</a></td></tr>";
        }
        html+="</table>";
        return html;
    }

    @RequestMapping("/delete")
    public void delete(String username, HttpServletResponse response){
        mapper.delete(username);
        try {
            response.sendRedirect("/select");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @RequestMapping("/update")
    public void update(@RequestBody User user,HttpServletResponse response){
        mapper.update(user);
    }
}
